<template>
  <div id="app"
       v-loading="loading.status"
       :element-loading-text="loading.txt"
       v-loading.fullscreen.lock="loading.full">
    <router-view />
  </div>
</template>
<script>
import adapter from "webrtc-adapter";
export default {
  data() {
    return {
      timer: '',
      longSocket: null,
      loading: {
        status: false,
        txt: '正在退出系统...',
        full: false,
      },
    }
  },
  created() {
    this.timer = setInterval(this.getToken, 600000)
    this.$once('hook:beforeDestroy', () => {
      clearInterval(this.timer)
      this.timer = null
    })
  },
  mounted() {
    console.log(this.$store.getters.leftMenuNav, '7778')
    this.checkIsGray()
    this.websocketInit()
    this.levelPlatform()
    this.getWebrtcFlag()
  },

  watch: {
    isoutlogin(newVal, oldVal) {
      if (newVal) {
        this.loginOut()
        if (this.longSocket) {
          let params = {
            type: 'login_out',
            token: sessionStorage.getItem('token'),
            terminal_type: 1,
          }
          this.longSocket.send(JSON.stringify(params))
        }
      }
    },
  },
  computed: {
    isoutlogin() {
      return this.$store.getters.outlogin
    },
  },
  beforeDestroy() {
    this.longSocket.close()
  },
  methods: {
    myBrowser() {
      let userAgent = navigator.userAgent //取得浏览器的userAgent字符串
      // 如果不是谷歌浏览器则返回false 
      if(userAgent.indexOf('Chrome') == -1) return false
      let num = userAgent.toLowerCase().match(/chrome\/([\d.]+)/)[1].split('.')[0]
      let isChrome = userAgent.indexOf('Chrome') > -1 && userAgent.indexOf('Safari') > -1 && num > 85//判断Chrome浏览器 85版本以上可用
      return isChrome

    },

    getWebrtcFlag() {
      let adapter_test = adapter.browserDetails.browser
      //检查是否允许webrtc
      if (adapter_test !== 'Not a supported browser.') {
        this.$store.commit('SET_WEBRTCFLAG', true)

        //判断是否允许开九个画面
        if (this.myBrowser()) {
          this.$store.commit('SET_ALLOWNINEFLAG', true)
        }
      }
        // 迭代前----------------------------------------------
        this.$store.commit('SET_WEBRTCFLAG', false)
        this.$store.commit('SET_ALLOWNINEFLAG', true)
    },
    getToken() {
      const success = (data) => {
        sessionStorage.setItem('token', data.data.token)
      }
      this.$ajax.get('api/login/login', { func: { success } })
    },
    /**
     * 检查是否多级平台 1为单机 ，2为多级
     * @DateTime 2020-08-11T15:40:53+0800
     * @qiu_m
     * @return   {[type]}                 [description]
     */
    levelPlatform() {
      //在页面刷新时将vuex里的信息保存到sessionStorage里
      window.addEventListener('beforeunload', () => {
        sessionStorage.setItem(
          'levelPlatform',
          JSON.stringify(this.$store.state)
        )
      })
      //在页面加载时读取sessionStorage里的状态信息
      if (sessionStorage.getItem('levelPlatform')) {
        this.$store.replaceState(
          Object.assign(
            {},
            this.$store.state,
            JSON.parse(sessionStorage.getItem('levelPlatform'))
          )
        )
      }
    },

    checkIsGray() {
      let success = (res) => {
        if (res.data.status === true) {
          document.getElementsByTagName('body')[0].classList.add('is-gray')
        } else {
          document.getElementsByTagName('body')[0].classList.remove('is-gray')
        }
      }

      this.$ajax.get('api/setting/gray', {
        params: {},
        headers: { DecisionPlatform: 'home' },
        func: { success: success },
      })
    },
    /**
     * websocket 连接，用户被修改后退出登录
     */
    websocketInit() {
      let webSocketURL = 'ws://' + this.BASE_URL.split(":")[1] + ':7474'
      this.longSocket = new WebSocket(webSocketURL)

      this.longSocket.onopen = (res) => {
        let params = {
          type: 'login',
          token: sessionStorage.getItem('token'),
          terminal_type: 1,
        }

        this.longSocket.send(JSON.stringify(params))
      }

      this.longSocket.onmessage = (res) => {
        let type = JSON.parse(res.data).type

        switch (type) {
          case 'outlogin':
            this.$message.error('该账号已被其他用户登录')
            setTimeout(() => {
              this.loginOut()
            }, 1000)
            break
          // case 'outlogin_one':
          //     !this.$store.getters.outlogin && this.$message.error('其他用户已退出该账号');
          //     this.loginOut();
          //     break;
          case 'delete_outlogin':
            this.$message.error('用户发送变化，请重新登录')
            setTimeout(() => {
              this.loginOut()
            }, 1000)
            break
          default:
            break
        }
      }

      this.longSocket.onclose = (res) => {}
    },
    /**
     * 退出账号
     */
    loginOut() {
      this.loading.txt = '正在退出系统...'
      this.loading.full = true

      this.$store.commit('SET_OUTLOGIN', false)

      if (JSON.parse(sessionStorage.getItem('user_info_str')).logout_url) {
        this.loading.txt = '退出成功...'
        this.loading.full = true
        let user_info_str = JSON.parse(sessionStorage.getItem('user_info_str'))

        setTimeout(() => {
          sessionStorage.clear()
          window.location.href = user_info_str.logout_url
        }, 800)
      } else {
        let success = (data) => {
          this.loading.txt = '退出成功...'
          this.loading.full = true
          let host_addr = sessionStorage.getItem('host_addr')

          setTimeout(() => {
            sessionStorage.clear()
            window.location.href = host_addr
          }, 800)
        }
        let fail = (data) => {
          this.$message.error(data.msg)
          this.loading.txt = data.msg
          this.loading.full = true

          setTimeout(() => {
            this.loading.status = false
            this.loading.full = false
          }, 800)
        }

        this.$ajax.delete('api/login/new_login', { func: { success, fail } })
      }
    },
  },
}
</script>

<<style lang="scss">
    .is-gray {
        -webkit-filter: grayscale(100%);
        -moz-filter: grayscale(100%);
        -ms-filter: grayscale(100%);
        -o-filter: grayscale(100%);
        filter: grayscale(100%);
        filter: gray;
    }
    .el-footer{
        white-space: pre;
    }
</style>
